﻿using System.Net;
using Microsoft.AspNetCore.Diagnostics;
using LowCoding.Common;

namespace LowCoding.API.Extensions
{
    public static class ExceptionMiddlewareExtensions
    {
        public static void UseGlobalExceptionHandler(this WebApplication app)
        {
            app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    context.Response.ContentType = "application/json";

                    var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
                    if (errorFeature != null)
                    {
                        await context.Response.WriteAsync(new ErrorResponse
                        {
                            StatusCode = (HttpStatusCode)context.Response.StatusCode,
                            Message = $"发生错误，错误信息：{errorFeature.Error.Message}，错误地址：{context.Request.Host}{context.Request.Path}"
                        }.ToJsonString());
                    }
                });
            });
        }
    }
}
